import * as fs from 'node:fs';
import * as path from 'node:path';

const apiDir = path.resolve(__dirname, '../src/api');
const backendDir = path.resolve(__dirname, '../src/backend');

// 确保 backend 目录存在
if (!fs.existsSync(backendDir)) {
  fs.mkdirSync(backendDir);
}

function transformContent(content: string): string {
  // 移除原有的导入
  content = content.replace(/import\s+request\s+from\s+["']@\/request["'];?\n?/, '');

  // 添加新的导入
  content = `import { request } from '@/utils/requestWrapper';\n\n${content}`;

  // 转换请求方法
  content = content.replace(
    /return request[<\w+>]*\(([\s\S]*?)\);/g,
    (match, params) => {
      // 解析参数
      const urlMatch = params.match(/"([^"]+)"/);
      const methodMatch = params.match(/method:\s*"(GET|POST)"/i);
      const dataMatch = params.match(/data:\s*([^,}]+)/);

      if (!urlMatch) return match;

      const url = urlMatch[1];
      const method = methodMatch ? methodMatch[1] : 'GET';
      const data = dataMatch ? dataMatch[1] : 'undefined';

      return `return request({
    url: "${url}",
    method: "${method}",
    data: ${data},
    ...options
  });`;
    }
  );

  return content;
}

function processFile(filePath: string) {
  const content = fs.readFileSync(filePath, 'utf-8');
  const fileName = path.basename(filePath);
  const newPath = path.join(backendDir, fileName);

  const transformedContent = transformContent(content);
  fs.writeFileSync(newPath, transformedContent);

}

// 处理所有 API 文件
fs.readdirSync(apiDir).forEach(file => {
  if (file.endsWith('.ts')) {
    processFile(path.join(apiDir, file));
  }
});
